package cn.wolfcode.crm.shiro;


import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.SystemLog;
import cn.wolfcode.crm.mapper.SystemLogMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.Servlet;
import java.util.Date;

//自定义日之类  用来统一保存日志,是一个切面
public class SystemLogAspect {

    @Autowired
    private SystemLogMapper systemLogMapper;

    public void writeLog(JoinPoint joinPoint) throws Exception {
        SystemLog log = new SystemLog();

        Employee employee = (Employee) SecurityUtils.getSubject().getPrincipal();
        if(employee != null){
        //用户
          log.setUserName(employee.getUserName());
        }
        //时间
        log.setActionTime(new Date());
        //方法
        String function  = joinPoint.getSignature().getDeclaringTypeName() + ":" + joinPoint.getSignature().getName();
        log.setFunction(function);

        //参数
        Object[] args = joinPoint.getArgs();
        String jsonString = new ObjectMapper().writeValueAsString(args);
        log.setParams(jsonString);
        //ip
        ServletRequestAttributes sqa = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String remoteAddr = sqa.getRequest().getRemoteAddr();
        log.setIp(remoteAddr);

        systemLogMapper.insert(log);

    }
}
